package com.weigang.webservice.config;

import com.weigang.webservice.interceptor.AuthInterceptor;
import com.weigang.webservice.service.impl.UserAuthInterceptorServerImpl;
import com.weigang.webservice.service.impl.UserServiceImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.ws.Endpoint;

@Configuration
public class CxfConfig {

    @Bean(name = "cxfServlet")
    public ServletRegistrationBean dispatcherServlet() {
        return new ServletRegistrationBean(new CXFServlet(), new String[]{"/ws/*"});
    }

    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }

    @Bean
    public UserServiceImpl userServiceImpl() {
        return new UserServiceImpl();
    }

    @Bean
    public Endpoint userServicePublish() {
        EndpointImpl endpoint = new EndpointImpl(this.springBus(), this.userServiceImpl());
        endpoint.publish("/userService");
        Server server = endpoint.getServer();
        org.apache.cxf.endpoint.Endpoint cxfEndpoint = server.getEndpoint();
        LoggingInInterceptor logging = new LoggingInInterceptor();
        cxfEndpoint.getInInterceptors().add(logging);
        System.out.println("Web service started..............");
        return endpoint;
    }

    @Bean
    public UserAuthInterceptorServerImpl userAuthInterceptorServerImpl() {
        return new UserAuthInterceptorServerImpl();
    }

    @Bean
    public Endpoint userAuthInterceptorServerPublish() {
        EndpointImpl endpoint = new EndpointImpl(this.springBus(), this.userAuthInterceptorServerImpl());
        endpoint.publish("/userAuthInterceptorServer");
        Server server = endpoint.getServer();
        org.apache.cxf.endpoint.Endpoint cxfEndpoint = server.getEndpoint();
        LoggingInInterceptor logging = new LoggingInInterceptor();
        cxfEndpoint.getInInterceptors().add(logging);
        cxfEndpoint.getInInterceptors().add(new AuthInterceptor());
        System.out.println("Web service started..............");
        return endpoint;
    }

}

